package com.base.servlet.message;

import com.base.servlet.http.HttpServletRequestWrapper;
import com.base.servlet.http.HttpServletResponseWrapper;
import com.base.servlet.http.HttpSession;
import com.base.servlet.http.HttpSessionFactory;
import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Map;

import static com.base.servlet.constant.HttpRequestHeaderKeyConstant.*;

/**
 * @author: Jeffrey
 * @date: 2022/01/23/9:30
 * @description:
 */
public class HttpConvert {

    private Channel channel;
    private static final String BLANK = " ";


    public HttpConvert(Channel channel) {
        this.channel = channel;
    }

    public HttpServletRequestWrapper convertToRequest(HttpMessage httpMessage){
        String method;
        String url;
        String license;
        Map<String,Object> parameterMap = new HashMap<>();

        Map<String,String> map;
        String uri;
        String host;
        String connection;
        String contentType;
        String contentLength;

        String body;

        HttpSession session = HttpSessionFactory.getSession();

        /*请求行解析*/
        String line = httpMessage.getLine();
        String[] lineSplit = line.split(BLANK);
        method = lineSplit[0];
        url = lineSplit[1];
        license = lineSplit[2];
        /*/login/login?hai=222&li=555*/
        String[] urlSplit = url.split("\\?");
        if(urlSplit.length > 1){
            String[] paramSplit = urlSplit[1].split("&");
            for (String s :paramSplit){
                String[] array = s.split("=");
                parameterMap.put(array[0],array[1]);
            }
        }



        /*请求头解析*/
        map = httpMessage.getHeader();
        host = map.get(HOST);
        connection = map.get(CONNECTION);
        contentType = map.get(CONTENT_TYPE);
        contentLength = map.get(CONTENT_LENGTH);
        uri = map.get(REFERER) == null ? host + url : map.get(REFERER);

        /*请求体解析*/
        body = httpMessage.getBody();

        HttpServletRequestWrapper httpRequest =
                new HttpServletRequestWrapper(method,
                        url,
                        uri,
                        map,
                        channel,
                        httpMessage,
                        parameterMap,
                        session
                        );
        return httpRequest;

    }

    public HttpMessage convertFromResponse(HttpServletResponseWrapper response){
        HttpMessage httpMessage = new HttpMessage();

        /*1.响应行*/
        String version = response.getVersion();
        int status = response.getStatus().getCode();
        String message = response.getStatus().getMessage();
        httpMessage.setLine(version+BLANK+status+BLANK+message);

        /*2.响应头*/
        httpMessage.setHeader(response.getHeaders());

        /*3.响应体*/
        httpMessage.setBody(response.getBody());
        return httpMessage;
    }
}
